#include "gamebody.hpp"

Creature player(CreatureName::PLAYER),
        target(CreatureName::WOOD_TARGET);

GameBody::GameBody(string title, int width, int height){
    SDL_Init(SDL_INIT_EVERYTHING);
    IMG_Init(IMG_INIT_JPG|IMG_INIT_PNG|IMG_INIT_TIF);
    TTF_Init();
    
    SDL_Log("init all");

    window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_SHOWN|SDL_WINDOW_RESIZABLE);
    assert(window!=nullptr);

    SDL_Log("Created Window");

    render = SDL_CreateRenderer(window, -1, 0);
    assert(render!=nullptr);

    SDL_Log("Created Render");
    
    canva = SDL_CreateTexture(render, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, width, height);
    assert(canva!=nullptr);
    SDL_SetRenderTarget(render, canva);

    SDL_Log("Created Canva");

    SDL_Log("Window size (%d, %d)", CANVA_WIDTH, CANVA_HEIGHT);
    SDL_Log("Game gride size (%d, %d)", GRID_COL, GRID_ROW);

    InitTextResources();

    charset = new CurseSheet;
    _controller = &GamingController::GetInstance();

    // NOTE init some demo object
    player.SetPosition(12, 12);
    target.SetPosition(14, 14);
    player.SetColor({0, 255, 0});
    target.SetColor({100, 0, 100});

    diary.AddText("Hello world");
    diary.AddText("Welcome to the rougelike");
}

void GameBody::Run(){
    while(!isquit){
        SDL_SetRenderDrawColor(render, 100, 100, 100, 255);
        SDL_RenderClear(render);
        eventHandle();
        step();
        SDL_Delay(30);
        SDL_SetRenderTarget(render, nullptr);
        SDL_RenderCopy(render, canva, nullptr, nullptr);
        SDL_RenderPresent(render);
        SDL_SetRenderTarget(render, canva);
    }
}

void GameBody::eventHandle(){
    while(SDL_PollEvent(&_event)){
        if(_event.type==SDL_QUIT)
            isquit = true;
        _controller->Control(_event, player);
    }
}

GameBody::~GameBody(){
    if(canva)
        SDL_DestroyTexture(canva);
    delete charset;
    ReleaseTextResources();
    TTF_Quit();
    IMG_Quit();
    SDL_Quit();
}

void GameBody::step(){
    Room room(10, 10, 10, 15);
    room.Draw();
    target.Draw();
    player.Draw();
    diary.Draw(0, 0, {0, 255, 0});
}
